package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 自动调用与Test2在同一个包中被AutoRunClass标注的类中被@AutoRun标注的方法
 */
public class Test2 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        File dir = new File(
                Test2.class.getResource(".").toURI()
        );
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File file : subs) {
            String className = file.getName().substring(
                    0, file.getName().indexOf(".")
            );
            Class cls = Class.forName("reflect." + className);
            if (!cls.isAnnotation() && cls.isAnnotationPresent(AutoRunClass.class) ){
                Object o = cls.newInstance();
                System.out.println("实例化：" + cls.getName());
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRun.class)) {
                        System.out.println("调用的方法：" + method.getName());
                        method.invoke(o);
                    }

                }
            }
        }
    }
}
